package com.muyu.service;

import com.muyu.service.UserService;
import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class MuyuBeanPostProcessor implements BeanPostProcessor {

    /*
    Spring创建任何bean都会调用下面两个方法
     */

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if("userService".equals(beanName)){
            System.out.println("初始化前");
            ((UserService) bean).setBeanName("木羽测试~初始化前");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("木羽测试~初始化后");

//        if(beanName.equals("userService")){
//            Object proxyInstance = Proxy.newProxyInstance(MuyuBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
//                @Override
//                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                    System.out.println("AOP动态代理");
//                    return method.invoke(bean, args);
//                }
//            });
//            return proxyInstance;
//        }

        return bean;
    }
}
